package com.dingding.queue.base.sms.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dingding.common.core.util.ToolUtil;
import com.dingding.queue.base.sms.ISendMessage;

/**
 * 
 * @ClassName: ChuangLanSendMessageImpl
 * @Description: 创蓝发送短信实现
 * @author CHEHAUNBO
 * @date 2016年2月24日 下午4:46:02
 * 
 */
@Component("chuangLanSendMessage")
public class ChuangLanSendMessageImpl implements ISendMessage {

	private static final Logger log = Logger.getLogger(ChuangLanSendMessageImpl.class);
	// 应用地址
	private static String url = "http://222.73.117.156/msg/HttpBatchSendSM";
	// 用户账户
	private static String account = "vip-dddc";
	// 用户密码
	private static String pswd = "Dddc888888";

	/**
	 * 
	 * @param tellphone
	 *            手机号码
	 * @param msg
	 *            短信内容
	 * @return true 成功 false 失败
	 * @throws Exception
	 * 
	 */
	@Override
	public boolean sendMessage(String tellphone, String msg) {

		if (ToolUtil.isBlank(tellphone) || ToolUtil.isBlank(msg)) {
			log.error("短信发送出现问题，存在空值！");
			return false;
		}

		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);

		try {

			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			// 用户账号（叮叮公司在创蓝注册的账号）
			formparams.add(new BasicNameValuePair("account", account));
			// 密码
			formparams.add(new BasicNameValuePair("pswd", pswd));
			// 发送短信的手机号
			formparams.add(new BasicNameValuePair("mobile", tellphone));
			// 发送短信的内容
			formparams.add(new BasicNameValuePair("msg", msg));
			// 是否需要状态报告，需要true，不需要false
			formparams.add(new BasicNameValuePair("needstatus", "true"));
			// 设置请求参数
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);

			httpPost.setEntity(entity);

			// 执行http请求
			CloseableHttpResponse httpResponse = client.execute(httpPost);

			// 获取状态码
			int resultCode = httpResponse.getStatusLine().getStatusCode();

			if (resultCode == HttpStatus.SC_OK) { // 请求成功
				String resultMsg = EntityUtils.toString(httpResponse.getEntity());
				if (ToolUtil.isNotBlank(resultMsg)) {
					
					String code = "";
					
					//没有换行说明返回的错误信息
					if(resultMsg.indexOf("\n") != -1){
						code = resultMsg.substring(resultMsg.indexOf(",") + 1, resultMsg.indexOf("\n"));
					}else{
						code = resultMsg.substring(resultMsg.indexOf(",") + 1);
					}
					
					if ("0".equals(code)) { // 短信发送成功
						return true;
					} else {
						log.error("短信发送失败! 错误码为：" + code);
						return false;
					}
				}
			}

		} catch (NullPointerException e) {
			log.error("发送短信出现异常！", e);
		} catch (UnsupportedEncodingException e) {
			log.error("发送短信出现异常！", e);
		} catch (IOException e) {
			log.error("发送短信出现异常！", e);
		} catch (Exception e) {
			log.error("发送短信出现异常！", e);
		}

		return false;

	}

}
